package com.dw.widget.slideshow.utils;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.Thread.UncaughtExceptionHandler;

import com.dw.widget.slideshow.utils.log.Log;

import android.content.Context;

public class CrashHandler implements UncaughtExceptionHandler{

	private static CrashHandler _instance;
	private final String TAG = "CrashHandler";
	
	private Context context;
	private UncaughtExceptionHandler defaultHandler;
	
	public static CrashHandler Instance()
	{
		if(_instance == null)
		{
			_instance = new CrashHandler();
		}
		
		return _instance;
	}
	
	public void init(Context context)
	{
		this.context = context;
		defaultHandler = Thread.getDefaultUncaughtExceptionHandler();
		Thread.setDefaultUncaughtExceptionHandler(this);
	}
	
	@Override
	public void uncaughtException(Thread thread, Throwable ex) {
		
		Writer info = new StringWriter();
        PrintWriter printWriter = new PrintWriter(info);
        ex.printStackTrace(printWriter);

        Throwable cause = ex.getCause();
        while (cause != null) {
            cause.printStackTrace(printWriter);
            cause = cause.getCause();
        }

        String result = info.toString();
        printWriter.close();
        
        Log.e(context, TAG, result);
	}

}
